package com.zmx.patients;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.model.Accounts;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.zmx.patients.listener.InformUpdateListenerManager;
import com.zmx.patients.view.util.CustomToast;
import com.zmx.patients.view.util.LoadingDialog;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static android.app.Notification.BADGE_ICON_SMALL;

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected LoadingDialog mLoadingDialog; //显示正在加载的对话框
    protected View positionView;
    protected Activity mActivity;

    public SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    public Toolbar toolbar;

    /**
     * 跳转到下一个activity
     **/
    protected static final int REQUEST_ACTIVITY = 10;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base);
        mActivity = this;
        //找到资源文件的XML
        if (getLayoutId() != 0) {

            View vContent = LayoutInflater.from(mActivity).inflate(getLayoutId(), null);
            ((FrameLayout) findViewById(R.id.frame_content)).addView(vContent);

        }

        InformUpdateListenerManager informUpdateListenerManager = new InformUpdateListenerManager(mActivity);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        createGroup();
        Observer<List<IMMessage>> incomingMessageObserver =
                new Observer<List<IMMessage>>() {
                    @Override
                    public void onEvent(List<IMMessage> messages) {

                        // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。

                        for (IMMessage im:messages){

                            Log.e("有新消息嘛我是家属端"+im.getSessionId(),"有没有"+im.getContent());

                        }

                        informUpdateListenerManager.getInstance(mActivity).updateData();
                        MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.unread_message,true);

                        if (messages.size()>0){

                            IMMessage im = messages.get(0);

                            if (im.getContent() != null && !im.getContent().equals("")){

                                try {

                                    JSONObject object = new JSONObject(im.getContent());
                                    Gson gson = new Gson();
                                    Log.e("成功", "object成功"+object.toString());
                                    String roomid = object.getString("roomID");

                                    notification("医生发起视频通话了！");
                                    ArrayList<Accounts> accounts = new ArrayList<>();
                                    JSONArray array = object.getJSONArray("accounts");
                                    for (int i = 0;i<array.length();i++){
                                        Accounts as = gson.fromJson(array.get(i).toString(),Accounts.class);
                                        accounts.add(as);

                                    }

                                    AVChatKit.outgoingTeamCall(mActivity, true, "1", roomid, accounts, "多方通话");

                                } catch (JSONException e) {

                                    notification(im.getContent());
                                    e.printStackTrace();

                                }

                            }

                        }


                    }
                };
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);


        initViews();
    }

    @Override
    public void onClick(View v) {


    }

    //避免用户使用手机字体导致屏幕适配问题
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            //非默认值
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    //避免用户使用手机字体导致屏幕适配问题
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }


    /**
     * 设置加载提示框
     */
    protected void showLoadingView(String message) {

        if (mLoadingDialog == null) {

            mLoadingDialog = new LoadingDialog(this, message, false);

        }
        mLoadingDialog.show();

    }

    /**
     * 数据加载完成
     */
    protected void dismissLoadingView() {

        if (mLoadingDialog != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLoadingDialog.hide();
                }
            });

        }

    }

    /**
     * 初始化Activity的常用变量 举例:
     * <b>mLayoutResID=页面XML资源ID 必须存在的</b>
     */
    protected abstract int getLayoutId();

    /**
     * 初始化视图
     **/
    protected abstract void initViews();

    /**
     * 通过Class跳转界面
     *
     * @param cls
     */
    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     *
     * @param cls
     * @param bundle
     */
    protected void startActivity(Class<?> cls, Bundle bundle) {
        startActivity(cls, bundle, REQUEST_ACTIVITY);
    }

    /**
     * 通过Class跳转界面
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    protected void startActivity(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(mActivity, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }


    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        Log.e("密码", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));
        Log.e("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        Log.e("role", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, ""));
        Log.e("时间戳", System.currentTimeMillis() / 1000 + "");

        requestparams.append(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();

    }

    public void setToolbar(int id) {

        ImmersionBar.with(this).titleBar(id).keyboardEnable(true).init();
        toolbar = findViewById(id);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//关闭页面
            }
        });
    }

    @Override
    protected void onDestroy() {

        if (mLoadingDialog != null) {

            mLoadingDialog.dismiss();

        }

        super.onDestroy();
    }

    public void Toast(String msg) {

        CustomToast.getInstance().showToastCustom(this, msg, Gravity.BOTTOM);

    }


    public static void Ksort(Map<String, String> map) {

        String sb = "";
        String[] key = new String[map.size()];
        int index = 0;
        for (String k : map.keySet()) {
            key[index] = k;
            index++;
        }
        Arrays.sort(key);
        for (String s : key) {
            sb += s + "=" + map.get(s) + "&";
        }
        sb = sb.substring(0, sb.length() - 1);
// 将得到的字符串进行处理得到目标格式的字符串
        try {
            sb = URLEncoder.encode(sb, "UTF-8");
        } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }// 使用常见的UTF-8编码
        sb = sb.replace("%3D", "=").replace("%26", "&");
        System.out.println(sb);
    }



    private NotificationManager mNotificationManager;

    private String groupId = "groupId";
    private CharSequence groupName = "Group1";

    private String groupId2 = "groupId2";
    private CharSequence groupName2 = "Group2";
    private String chatChannelId2 = "chatChannelId2";
    private String adChannelId2 = "adChannelId2";

    private String chatChannelId = "chatChannelId";
    private String chatChannelName = "聊天通知";
    private String chatChannelDesc = "这是一个聊天通知，建议您置于开启状态，这样才不会漏掉女朋友的消息哦";
    private int chatChannelImportance = NotificationManager.IMPORTANCE_MAX;

    private String adChannelId = "adChannelId";
    private String adChannelName = "广告通知";
    private String adChannelDesc = "这是一个广告通知，可以关闭的，但是如果您希望我们做出更好的软件服务于你，请打开广告支持一下吧";
    private int adChannelImportance = NotificationManager.IMPORTANCE_LOW;

    public void notification(String context) {
        createNotificationChannel(chatChannelId, chatChannelName, chatChannelImportance, chatChannelDesc, groupId2);

        Notification.Builder builder = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, chatChannelId);
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("有新消息啦！")
                    .setContentText(context)
                    .setBadgeIconType(BADGE_ICON_SMALL)
                    .setNumber(1)
                    .setAutoCancel(true);
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(resultPendingIntent);

            mNotificationManager.notify((int) System.currentTimeMillis(), builder.build());
        }

    }

    public void notification2() {
        createNotificationChannel(adChannelId, adChannelName, adChannelImportance, adChannelDesc, groupId2);

        Notification.Builder builder = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, adChannelId);
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("我是广告")
                    .setContentText("内容：恰饭时间到了，Oreo is Coming.")
                    .setBadgeIconType(BADGE_ICON_SMALL)
                    .setNumber(1)
                    .setAutoCancel(true);

            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(resultPendingIntent);
            mNotificationManager.notify((int) System.currentTimeMillis(), builder.build());
        }

    }

    public void createNotificationChannel(String id, String name, int importance, String desc, String groupId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (mNotificationManager.getNotificationChannel(id) != null) {
                return;
            }

            NotificationChannel notificationChannel = new NotificationChannel(id, name, importance);
            notificationChannel.enableLights(true);
            notificationChannel.enableVibration(true);

            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationChannel.setShowBadge(true);
            notificationChannel.setBypassDnd(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400});
            notificationChannel.setDescription(desc);
            notificationChannel.setGroup(groupId);
//        notificationChannel.setSound();

            mNotificationManager.createNotificationChannel(notificationChannel);

        }

    }

    public void delNotification(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.deleteNotificationChannel(chatChannelId);
        }
    }

    public void delNotification2(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.deleteNotificationChannel(adChannelId);
        }
    }

    public void setting(View view) {
        Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
        intent.putExtra(Settings.EXTRA_CHANNEL_ID, chatChannelId);
        intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
        startActivity(intent);
    }

    public void createGroup() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId, groupName));
            mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId2, groupName2));
            createNotificationChannel(chatChannelId2, chatChannelName, chatChannelImportance, chatChannelDesc, groupId);
            createNotificationChannel(adChannelId2, adChannelName, adChannelImportance, adChannelDesc, groupId);
        }
    }

    public void delNotificationGroup(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.deleteNotificationChannelGroup(groupId2);
        }

    }



}